import {
    _decorator, Component, Node, Label, Sprite,
    SpriteFrame, assetManager, ImageAsset, Texture2D, sys, director,
    Button, Color
} from 'cc';
import {SocketLogicInterface} from "db://assets/scripts/interface/SocketLogicInterface";
import {SocketMessage} from '../dto/SocketMessage';
import {WebsocketMgr} from "db://assets/scripts/component/WebsocketMgr";
import {WxUser} from "db://assets/scripts/dto/WxUser";
import {RoofInfoDTO} from "db://assets/scripts/dto/RoofInfoDTO";
import {ClientInfoDTO} from "db://assets/scripts/dto/ClientInfoDTO";
import {get, post} from "db://assets/scripts/config/Api";
import {Message} from "db://assets/scripts/component/Message";
import {Modal} from "db://assets/scripts/component/Modal";

const {ccclass, property} = _decorator;
const wx = window['wx'];

@ccclass('GameRoomControl')
export class GameRoomControl extends Component implements SocketLogicInterface {

    userInfo: WxUser;
    roomInfo: RoofInfoDTO = null;

    @property(Label)
    title: Label = null!;

    @property(Sprite)
    user1Head: Sprite = null!;
    @property(Label)
    user1Name: Label = null!;


    @property(Sprite)
    user2Head: Sprite = null!;
    @property(Label)
    user2Name: Label = null!;

    @property(Label)
    user2Status: Label = null!;

    userData: ClientInfoDTO = null;
    userDataTwo: ClientInfoDTO = null;

    currentUserData: ClientInfoDTO = null;
    otherUserData: ClientInfoDTO = null;

    @property(Node)
    marsk: Node = null!;

    @property(Button)
    invitedBtn: Button = null!;

    homeowners: boolean = false;

    defaultUser2Head: SpriteFrame;

    start() {
        this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
        this.defaultUser2Head = this.user2Head.spriteFrame;
        this.subscription();

        if (localStorage.getItem('roofInfo')) {
            this.roomInfo = JSON.parse(localStorage.getItem('roofInfo'));
            this.getUserInfo();
            this.updateRoomInfo();
        } else {
            this.joinRoom();
        }

    }

    update(deltaTime: number) {

    }

    subscription() {
        WebsocketMgr.inst.initSocket();
        WebsocketMgr.inst.socketLogic.set(this.getPatch(), this);
    }

    accept(message: SocketMessage) {
        let events = message.event.split('/');
        // 等待
        if (events[1] === "joinRoomFail") {
            this.joinRoomFail(message);
            return;
        } else if (events[1] === "joinRoomSuccess") {
            this.joinRoomSuccess(message);
            return;
        } else if (events[1] === "disbandedRoomSuccess") {
            this.disbandedRoomSuccess(message);
            return;
        } else if (events[1] === "otherUpdatePlayerStatus") {
            this.otherUpdatePlayerStatus(message);
            return;
        } else if (events[1] === "StartGame") {
            this.startGame(message);
            return;
        } else if (events[1] === "otherExitRoom") {
            this.otherExitRoom(message);
            return;
        }
    }

    getPatch(): string {
        return "GameRoom";
    }

    private async getUserInfo() {
        try {
            this.userData = null;
            this.userDataTwo = null;
            this.currentUserData = null;
            this.otherUserData = null;

            // 房主
            this.userData = this.roomInfo.players[0];
            if (this.roomInfo.players.length > 1)
                this.userDataTwo = this.roomInfo.players[1];

            if (this.userData && this.userData.currentPlayer.id === this.userInfo.id) {
                this.currentUserData = this.userData;
                this.otherUserData = this.userDataTwo;
                this.homeowners = true;
            }
            if (this.userDataTwo && this.userDataTwo.currentPlayer.id === this.userInfo.id) {
                this.currentUserData = this.userDataTwo;
                this.otherUserData = this.userData;
            }
        } catch (e) {
            console.error(e)
        } finally {
            console.log("结束")

        }

    }

    private updateRoomInfo() {
        if (this.roomInfo.gameType === "2048") {
            this.title.string = "2048道具战";
        } else if (this.roomInfo.gameType === "xiaoxiaole") {
            this.title.string = "消消乐";
        }
        this.user1Name.string = this.userData.currentPlayer.wxUsername;
        // 从url设置头像
        assetManager.loadRemote<ImageAsset>(this.userData.currentPlayer.wxHead, (err, imageAsset) => {
            const spriteFrame = new SpriteFrame();
            const texture = new Texture2D();
            texture.image = imageAsset;
            spriteFrame.texture = texture;
            this.user1Head.spriteFrame = spriteFrame;
        });

        if (this.userDataTwo) {
            this.user2Name.string = this.userDataTwo.currentPlayer.wxUsername;
            // 从url设置头像
            assetManager.loadRemote<ImageAsset>(this.userDataTwo.currentPlayer.wxHead, (err, imageAsset) => {
                const spriteFrame = new SpriteFrame();
                const texture = new Texture2D();
                texture.image = imageAsset;
                spriteFrame.texture = texture;
                this.user2Head.spriteFrame = spriteFrame;
            });
        } else {
            this.user2Name.string = "等待邀请";
            this.user2Head.spriteFrame = this.defaultUser2Head;
        }
        this.updateInvitedBtn();
    }

    private updateInvitedBtn() {

        // 用户2下面已准备文案
        if (this.userDataTwo) {
            this.user2Status.node.active = true;
            if (this.userDataTwo.status === 1) {
                this.user2Status.string = "已准备";
                this.user2Status.color = new Color().fromHEX("#15F02F");
            } else {
                this.user2Status.string = "未准备";
                this.user2Status.color = new Color().fromHEX("#575757");
            }
        } else {
            this.user2Status.node.active = false;
        }


        if (!this.userDataTwo) {
            this.invitedBtn.node.children[0].getComponent(Label).string = "邀请好友";
            return;
        }
        // 是房主
        if (this.homeowners) {
            this.invitedBtn.node.children[0].getComponent(Label).string = "开始";

            if (this.otherUserData.status === 0) {
                this.invitedBtn.interactable = false;
            } else {
                this.invitedBtn.interactable = true;
            }
            return;
        }

        // 不是房主
        if (this.currentUserData.status === 1) {
            this.invitedBtn.node.children[0].getComponent(Label).string = "已准备";
        } else {
            this.invitedBtn.node.children[0].getComponent(Label).string = "未准备";
        }


    }

    private invited() {
        if (this.invitedBtn.node.children[0].getComponent(Label).string === "邀请好友") {
            wx.shareAppMessage({
                title: `我是${this.userInfo.wxUsername}, 不服来战!`,
                query: `roomId=${this.roomInfo.roofNo}`,
            });
            return;
        }
        if (this.invitedBtn.node.children[0].getComponent(Label).string === "开始") {
            this.sendStartGame();
            return;
        }
        if (this.invitedBtn.node.children[0].getComponent(Label).string === "已准备") {
            this.currentUserData.status = 0;
            let socketMessag: SocketMessage = new SocketMessage();
            socketMessag.event = "updatePlayerStatus";
            socketMessag.data = this.currentUserData.status;
            socketMessag.message = "GameRoom";
            WebsocketMgr.inst.sendMessage(socketMessag);
            this.updateInvitedBtn();
            return;
        }
        if (this.invitedBtn.node.children[0].getComponent(Label).string === "未准备") {
            this.currentUserData.status = 1;
            let socketMessag: SocketMessage = new SocketMessage();
            socketMessag.event = "updatePlayerStatus";
            socketMessag.data = this.currentUserData.status;
            socketMessag.message = "GameRoom";
            WebsocketMgr.inst.sendMessage(socketMessag);
            this.updateInvitedBtn();
            return;
        }
    }

    private async createGetUserNickName() {
        this.marsk.active = true;
        let info = wx.getSystemInfoSync();
        let button = wx.createUserInfoButton({
            type: 'text',
            text: '点击获取用户信息',
            style: {
                left: info.screenWidth / 2 - 100,
                top: 300,
                width: 200,
                height: 40,
                lineHeight: 40,
                backgroundColor: '#8D99D5',
                color: '#ffffff',
                textAlign: 'center',
                fontSize: 16,
                borderRadius: 4
            }
        })
        button.onTap(async (res) => {
            console.log("结果::", res.userInfo);

            button.hide();
            this.marsk.active = false;
            await this.setUserInfo(res.userInfo);
            this.joinRoom();
        })
    }

    private async setUserInfo(userInfo: {
        avatarUrl: string;
        nickName: string;
    }) {
        console.log("用户头像" + userInfo.avatarUrl);
        console.log("用户昵称" + userInfo.nickName);
        let res = await post("/wx/updateUser", {
            "nickName": userInfo.nickName,
            "headUrl": userInfo.avatarUrl,
        })

        await this.getMe(sys.localStorage.getItem("token"));
    }

    private async getMe(token: string) {
        let resultMe = await get<WxUser>("/wx/me");
        sys.localStorage.setItem('userInfo', JSON.stringify(resultMe));
        this.userInfo = JSON.parse(sys.localStorage.getItem("userInfo"));
    }


    private joinRoom(): boolean {
        if (!this.userInfo.wxHead) {
            this.createGetUserNickName();
            return true;
        }
        console.log("加入房间")

        // 已在房间
        if (this.userData && this.userInfo.id === this.userData.currentPlayer.id) {
            return false;
        }
        if (this.userDataTwo && this.userInfo.id === this.userDataTwo.currentPlayer.id) {
            return false;
        }
        console.log("发送加入房间信息")

        let socketMessag: SocketMessage = new SocketMessage();
        socketMessag.event = "joinRoom";
        socketMessag.data = sys.localStorage.getItem("roomId");
        WebsocketMgr.inst.sendMessage(socketMessag);

        console.log("发送加入房间信息成功")

        return true;
    }

    private joinRoomFail(message: SocketMessage) {
        Message.Instance.show(message.data);
        this.scheduleOnce(() => {
            director.loadScene("home");
        }, 2);
    }

    private joinRoomSuccess(message: SocketMessage) {
        sys.localStorage.setItem("roofInfo", JSON.stringify(message.data));
        this.roomInfo = JSON.parse(localStorage.getItem('roofInfo'));
        this.getUserInfo();
        this.updateRoomInfo();
    }

    private clickHome() {
        if (this.userData.currentPlayer.id === this.userInfo.id) {
            Modal.Instance.show("退出房间", "你是房主,退出房间会导致房间解散,是否强行退出房间!", () => {

                let socketMessag: SocketMessage = new SocketMessage();
                socketMessag.event = "exitRoom";
                socketMessag.data = "GameRoom";
                WebsocketMgr.inst.sendMessage(socketMessag);

                sys.localStorage.removeItem("roofInfo");
                director.loadScene("home");
            });
        } else {
            Modal.Instance.show("退出房间", "退返回会离开好友的房间,是否退出房间", () => {
                let socketMessag: SocketMessage = new SocketMessage();
                socketMessag.event = "exitRoom";
                socketMessag.data = "GameRoom";
                WebsocketMgr.inst.sendMessage(socketMessag);
                sys.localStorage.removeItem("roofInfo");
                director.loadScene("home");
            });
        }
    }

    private disbandedRoomSuccess(message: SocketMessage) {
        Message.Instance.show("房主已解散房间");
        this.scheduleOnce(() => {
            director.loadScene("home");
        }, 2);
    }


    private otherUpdatePlayerStatus(message: SocketMessage) {
        this.otherUserData.status = message.data.status;
        this.updateInvitedBtn();
    }

    private sendStartGame() {
        let socketMessag: SocketMessage = new SocketMessage();
        socketMessag.event = "roomStartGame";
        socketMessag.message = "GameRoom";
        WebsocketMgr.inst.sendMessage(socketMessag);
    }

    private startGame(message: SocketMessage) {
        sys.localStorage.setItem("roofInfo", JSON.stringify(message.data));
        if (message.data?.gameType === "2048") {
            director.loadScene("gameMany2048")
        } else {
            director.loadScene("xiaoxiaoleManey")
        }
    }

    private otherExitRoom(message: SocketMessage) {
        console.log("其他用户退出房间")
        sys.localStorage.setItem("roofInfo", JSON.stringify(message.data));
        this.roomInfo = message.data;
        this.getUserInfo();
        this.updateRoomInfo();
    }
}


